<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/03/20
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use Imi\Cache\CacheManager as Cache;
use Imi\Config;
// use ImiApp\ApiServer\Api\Controller\Tpmecms;

/**
 * 运费模版
 * @Auth(name="token",nologin={"no"})
 * @Controller("/store.dispatch/")
 */
class Dispatch extends StoreOwner
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 添加运费模版
     *
     * @param string $name 模版名称
     * @param string $type 发货方式:express=快递,selfetch=用户自提,store=商户配送,autosend=自动发货
     * @param string $type_ids 包含模板
     * @return void
     * @Action
     */
    public function add($name = null, $type = null)
    {
        $this->init();
        $this->isRun();
        // 判断是否已经实名认证了
        // $this->VerifyRealName();

        $data['name'] = $name;
        $data['type'] = $type;
        $data['createtime'] = time();
        $data['updatetime'] = time();
        $data['store_id'] = $this->store_id;
        $data['id'] = Db::name('dispatch')->insert($data)->getLastInsertId();

        return $this->success('添加成功', $data);
    }


    /**
     * 编辑运费模版名
     * @param int $id 模版id
     * @param string $name 模版名称
     * @return void
     * @Action
     */
    public function edit(?int $id = null, $name = null)
    {
        $this->init();
        $this->isRun();
        // 判断是否已经实名认证了
        // $this->VerifyRealName();

        $data['name'] = $name;
        $data['updatetime'] = time();
        $res = Db::name('dispatch')->where('store_id', '=', $this->store_id)->where('id', '=', $id)->update($data);
        return $this->success('编辑成功', $res);
    }

    /**
     * 删除运费模版
     * @param int $id 模版id
     * @return void
     * @Action
     */
    public function del(?int $id = null)
    {
        $this->init();
        $this->isRun();
        // 判断是否已经实名认证了
        // $this->VerifyRealName();
        $data['deletetime'] = time();
        $res = Db::name('dispatch')->where('store_id', '=', $this->store_id)->where('id', '=', $id)->update($data);
        // $this->UpdateDispatchIds($id);
        return $this->success('删除成功', $res);
    }

    /**
     * 获取运费模版列表
     *
     * @return void
     * @Action
     */
    public function get_list()
    {
        $this->init();

        $list = Db::name('dispatch')->where('store_id', '=', $this->store_id)->whereIsNull('deletetime')->select()->getArray();
        if ($list) {
            foreach ($list as $key => $val) {
                // ['list'] = $this->getSubList($val);
                $data = $this->getSubList($val);
                if ($data)
                    $list[$key]['list'] = $data;
            }
        }
        // var_dump($list);
        return $this->success('列表', $list);
    }

    /**
     * 获取运费模版详情
     * 
     * @param int $id 模版id
     * @return void
     * @Action
     */
    public function get_details($id)
    {
        $this->init();

        $val = Db::name('dispatch')->where('store_id', '=', $this->store_id)->whereIsNull('deletetime')->where('id', '=', $id)->find();
        if ($val) {
            $val['list'] = $this->getSubList($val);
        }
        return $this->success('详情', $val);
    }

    /**
     * 添加快递运费列表
     * 
     * @param string $dispatch_id 模版id
     * @param string $first_num 首件
     * @param string $first_price 首件价格(必传)
     * @param string $additional_num 续件数量
     * @param string $additional_price 需件价格
     * @param string $province_ids 省ids(选其中1)
     * @param string $city_ids 市ids(选其中1)
     * @param string $town_ids 乡镇(选其中1)
     * @param string $district_ids 区(选其中1)
     * @param string $type 计费方式:number=件数,weight=重量
     * @param string $weigh 权重
     * @return void
     * @Action
     */
    public function add_express($dispatch_id = null, $type = 'number', $weigh = null, $first_num = null, $first_price = null, $additional_num = null, $additional_price = null, $province_ids = null, $city_ids = null, $town_ids = null, $district_ids = null)
    {
        $this->init();

        if (!$type || $type != 'weight') {
            $type = 'number';
        }
        $data['store_id'] = $this->store_id;
        $data['dispatch_id'] = $dispatch_id;
        $data['type'] = $type;
        $data['weigh'] = $weigh;
        $data['first_num'] = $first_num;
        $data['first_price'] = $first_price;
        $data['additional_num'] = $additional_num;
        $data['additional_price'] = $additional_price;
        $data['province_ids'] = $province_ids;
        $data['city_ids'] = $city_ids;
        $data['town_ids'] = $town_ids;
        $data['town_ids'] = $town_ids;
        $data['district_ids'] = $district_ids;
        $data['createtime'] = time();
        $data['updatetime'] = time();
        $data['id'] = Db::name('dispatch_express')->insert($data)->getLastInsertId();
        $this->UpdateDispatchIds($dispatch_id);
        return $this->success('添加成功', $data);
    }

    /**
     * 添加快递运费列表
     * 
     * @param int $快递id
     * @param int $dispatch_id 模版id
     * @param string $first_num 首件
     * @param string $first_price 首件价格(必传)
     * @param string $additional_num 续件数量
     * @param string $additional_price 需件价格
     * @param string $province_ids 省ids(选其中1)
     * @param string $city_ids 市ids(选其中1)
     * @param string $town_ids 乡镇(选其中1)
     * @param string $district_ids 区(选其中1)
     * @param string $type 计费方式:number=件数,weight=重量
     * @param int $weigh 权重
     * @return void
     * @Action
     */
    public function edit_express($id = null, $dispatch_id = null, $type = 'number', $weigh = null, $first_num = null, $first_price = null, $additional_num = null, $additional_price = null, $province_ids = null, $city_ids = null, $town_ids = null, $district_ids = null)
    {
        $this->init();

        if (!$type || $type != 'weight') {
            $type = 'number';
        }
        if ($weigh)
            $data['weigh'] = $weigh;
        if ($first_price)
            $data['first_num'] = $first_num;
        if ($first_price)
            $data['first_price'] = $first_price;
        if ($additional_num)
            $data['additional_num'] = $additional_num;
        if ($additional_price)
            $data['additional_price'] = $additional_price;
        if ($province_ids)
            $data['province_ids'] = $province_ids;
        if ($city_ids)
            $data['city_ids'] = $city_ids;
        if ($town_ids)
            $data['town_ids'] = $town_ids;
        if ($district_ids)
            $data['district_ids'] = $district_ids;
        $data['updatetime'] = time();
        $res = Db::name('dispatch_express')->where('store_id', '=', $this->store_id)->where('dispatch_id', '=', $dispatch_id)->where('id', '=', $id)->update($data);
        // $this->UpdateDispatchIds($dispatch_id);
        return $this->success('编辑成功', $data);
    }



    /**
     * 删除快递运费
     * @param int $id 模版id
     * @return void
     * @Action
     */
    public function del_express(?int $id = null)
    {
        $this->init();
        $this->isRun();
        // 判断是否已经实名认证了
        // $this->VerifyRealName();
        $data['deletetime'] = time();
        $res = Db::name('dispatch_express')->where('store_id', '=', $this->store_id)->where('id', '=', $id)->update($data);
        // $this->UpdateDispatchIds($id);
        return $this->success('删除成功', $res);
    }



    /**
     * 更新模版
     *
     * @param int $id 模版id
     * @return void
     */
    protected function UpdateDispatchIds($id)
    {
        $dispatch = Db::name('dispatch')->where('id', '=', $id)->find();
        switch ($dispatch['type']) {
            case 'express':
                $ids_arr = Db::name('dispatch_express')->where('dispatch_id', '=', $id)->whereIsNull('deletetime')->column('id');
                Db::name('dispatch')->where('id', '=', $id)->update(['type_ids' => implode(',', $ids_arr)]);
                break;

            default:
                # code...
                break;
        }
    }

    /**
     * 获取子列表参数
     *
     * @param array $data 参数
     * @return void
     */
    protected function getSubList($data)
    {
        $list2 = null;
        //发货方式:express=快递,selfetch=用户自提,store=商户配送,autosend=自动发货
        switch ($data['type']) {
            case 'express':
                $list = Db::name('dispatch_express')->where('store_id', '=', $this->store_id)->where('dispatch_id', '=', $data['id'])->whereIsNull('deletetime')->select()->getArray();
                if ($list) {
                    foreach ($list as $key => $data) {
                        $list[$key] =  $this->ChangeDispatchExpress($data);
                        // $data = $this->ChangeDispatchExpress($data);
                    }
                    $list2 = $list;
                } else {
                }

                break;

            default:
                # code...
                break;
        }
        return $list2;
    }

    /**
     * 快递
     *
     * @param array $data
     * @return void
     */
    protected function ChangeDispatchExpress($data)
    {
        if ($data['province_ids'])
            $data['province_list'] = Db::name('area')->where('level', '=', 1)->whereIn('id', explode(',', $data['province_ids']))->fieldRaw('name,id')->select()->getArray();

        if ($data['city_ids'])
            $data['city_list'] = Db::name('area')->where('level', '=', 2)->whereIn('id', explode(',', $data['city_ids']))->fieldRaw('name,id')->select()->getArray();

        if ($data['district_ids'])
            $data['district_list'] = Db::name('area')->where('level', '=', 3)->whereIn('id', explode(',', $data['district_ids']))->fieldRaw('name,id')->select()->getArray();

        if ($data['town_ids'])
            $data['town_list'] = Db::name('area')->where('level', '=', 4)->whereIn('id', explode(',', $data['town_ids']))->fieldRaw('name,id')->select()->getArray();
        return $data;
    }





    /**
     * 获取地区信息去除已有的模版地址
     * @param int $dispatch_id 模版id
     * @param string $province 省
     * @param string $city 市
     * @param string $district 区
     * @param string $town 街道或镇
     * @return void
     * @Action
     */
    public function get_area($dispatch_id = null, $province = null, $city = null, $district = null, $town = null)
    {
        $where_dispatch['dispatch_id'] = $dispatch_id;
        $Addr = new \ImiApp\ApiServer\Api\Controller\Addr;
        // $Addr->GetAreaId($province, $city, $district, $town);
        $db = 'area';
        // var_dump($Addr);

        $arr = [];
        //查询已经有的省

        $field = 'province_ids';
        $排除地区的数组 = Db::name('dispatch_express')->whereEx($where_dispatch)->whereIsNotNull($field)->column($field);
        if ($排除地区的数组) {
            //循环
            foreach ($排除地区的数组 as $key => $val) {
                if (!empty($val)) {
                    $temp = explode(',', $val);
                    $arr = array_merge($temp, $arr);
                }
            }
        }


        $field = 'city_ids';
        $排除地区的数组 = Db::name('dispatch_express')->whereEx($where_dispatch)->whereIsNotNull($field)->column($field);
        if ($排除地区的数组) {
            //循环
            foreach ($排除地区的数组 as $key => $val) {
                if (!empty($val)) {
                    $temp = explode(',', $val);
                    $arr = array_merge($temp, $arr);
                }
            }
        }


        $field = 'town_ids';
        $排除地区的数组 = Db::name('dispatch_express')->whereEx($where_dispatch)->whereIsNotNull($field)->column($field);
        if ($排除地区的数组) {
            //循环
            foreach ($排除地区的数组 as $key => $val) {
                if (!empty($val)) {
                    $temp = explode(',', $val);
                    $arr = array_merge($temp, $arr);
                }
            }
        }

        $field = 'area_ids';
        $排除地区的数组 = Db::name('dispatch_express')->whereEx($where_dispatch)->whereIsNotNull($field)->column($field);
        if ($排除地区的数组) {
            //循环
            foreach ($排除地区的数组 as $key => $val) {
                if (!empty($val)) {
                    $temp = explode(',', $val);
                    $arr = array_merge($temp, $arr);
                }
            }
        }


        $field = 'district_ids';
        $排除地区的数组 = Db::name('dispatch_express')->whereEx($where_dispatch)->whereIsNotNull($field)->column($field);
        if ($排除地区的数组) {
            //循环
            foreach ($排除地区的数组 as $key => $val) {
                if (!empty($val)) {
                    $temp = explode(',', $val);
                    $arr = array_merge($temp, $arr);
                }
            }
        }

        $arr = array_unique($arr);
        if (!$arr) {
            $arr = [99999999];
        }

        if (!$province) {
            $list = Db::name($db)
                ->where('pid', '=', 0)
                ->where('level', '=', 1)
                ->whereNotIn('id', $arr)
                ->select()->getArray();

            return $this->success($province, $list);
        }

        if (!$city) {
            $list = Db::name($db)
                ->where('pid', '=', $Addr->get_province_id($province))
                ->where('level', '=', 2)
                ->whereNotIn('id', $arr)
                // ->where('name',$province)
                ->select()->getArray();
            return $this->success($province, $list);
        }

        if (!$district) {
            $list = Db::name($db)
                ->where('pid', '=', $Addr->get_city_id($city))
                ->whereNotIn('id', $arr)
                // ->where('name','=',$city)
                ->select()->getArray();
            return $this->success($city, $list);
        }
        if (!$town) {
            $list = Db::name($db)
                ->where('pid', '=', $Addr->get_city_id($city))
                ->whereNotIn('id', $arr)
                // ->where('pid', '=',$Addr->get_district_id($district))
                ->select()->getArray();
            return $this->success($district, $list);
        } else {
            $data = Db::name($db)
                // ->where('pid','=', $Addr->get_city_id($city))
                ->where('pid', '=', $Addr->get_district_id($district))
                ->where('name', '=', $town)
                ->whereNotIn('id', $arr)
                ->select()->get();
            return $this->success($city, $data);
        }
    }
}
